﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;
using UserSurface;
using ApplicationCore;

namespace EnzymeLaborTool
{
    public partial class ParameterFrm : KryptonForm
    {
        public ParameterFrm()
        {
            InitializeComponent();
        }

        private MainSurface _surface;
        private EnzymeDBDataContext _dataContext;

        /// <summary>
        /// Initialize dialog with data context using main surface class
        /// </summary>
        /// <param name="ms"></param>
        public void Init(MainSurface ms)
        {
            _surface = ms;
            _dataContext = ms.GetDataContext();
            BindParameter();
        }

        #region Binding
        private void BindParameter()
        {
            var q = from x in _dataContext.ParameterViews orderby x.Name select x;
            parameterViewBindingSource.DataSource = q;
        }

        #endregion

        #region CRUD Parameter
        //toolbar initiated add-action
        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            if (!parameterDataGridView.IsCurrentCellInEditMode)
            {
                parameterViewBindingSource.AddNew();
                parameterDataGridView.BeginEdit(true);
            }
        }

        //create a default Material for adding
        private void parameterViewBindingSource_AddingNew(object sender, AddingNewEventArgs e)
        {
            e.NewObject = new ParameterView { Name = "NewParameter", Datatype = "NUMBER", Unit = "", Description = "" };
        }

        //validate added or updated material data
        private void parameterDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (parameterDataGridView.IsCurrentCellInEditMode)
            {
                var pv = parameterDataGridView.Rows[e.RowIndex].DataBoundItem as ParameterView;
                if (pv == null)
                {
                    return;
                }
                var col = parameterDataGridView.Columns[e.ColumnIndex];
                if (col.DataPropertyName == "Name")
                {
                    var check = _dataContext.Parameters.SingleOrDefault(x => x.UId != pv.UId && x.Name.ToLower() == e.FormattedValue.ToString().ToLower().Trim());
                    if (check != null)
                    {
                        parameterDataGridView.Rows[e.RowIndex].ErrorText = "A Parameter with this name already exist.";
                        e.Cancel = true;
                    }
                }
            }
        }

        //save added and updated material
        private void parameterDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            parameterDataGridView.Rows[e.RowIndex].ErrorText = null;
            ParameterView pv = null;
            try
            {
                pv = parameterDataGridView.Rows[e.RowIndex].DataBoundItem as ParameterView;
            }
            catch (IndexOutOfRangeException)
            {
                //handles case where new row is edited and then escape key is pressed to cancel the new row
            }

            if (pv != null)
            {
                if (pv.UId == Guid.Empty)
                {
                    pv.UId = _surface.AddParameter(pv.Name, pv.Datatype, pv.IsSplitVariable);
                }
                else
                {
                    _surface.UpdateParameter(pv.UId, pv.Name, pv.Datatype, pv.Unit, pv.IsSplitVariable,  pv.Description);
                }
            }
        }

        //toolbar initiated delete-action
        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            if (ConfirmParameterDelete())
            {
                ParameterView  mv = parameterViewBindingSource.Current as ParameterView;
                if (mv != null)
                {
                    _surface.DeleteParameter(mv.UId);
                    parameterViewBindingSource.RemoveCurrent();
                }
            }
        }

        //gridview initiated delete-action
        private void parameterDataGridView_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            e.Row.Tag = e.Row.DataBoundItem;
            e.Cancel = !ConfirmParameterDelete();
        }

        //delete parameter 
        private void parameterDataGridView_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            var pv = e.Row.Tag as ParameterView;
            if (pv != null)
            {
                _surface.DeleteParameter(pv.UId);
            }
        }

        //request user confirmation for delete
        private bool ConfirmParameterDelete()
        {
            return MessageBox.Show("Are you sure you want to delete the current parameter? All information regarding this parameter getting lost!", "Confirm parameter delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                == DialogResult.Yes;
        } 
        #endregion

        private void kryptonButton1_Click(object sender, EventArgs e)
        {
            Close();
        }

    }
}
